
package com.yimixian.app.ui;

import com.ta.utdid2.android.utils.StringUtils;
import com.yimixian.app.R;
import com.yimixian.app.SystemFramework;
import com.yimixian.app.rest.response.Error;
import com.yimixian.app.util.NetworkUtils;
import com.yimixian.app.util.SharedPreferencesHelper;
import com.yimixian.app.util.Strings;
import com.yimixian.app.util.UiUtils;
import com.ymx.sdk.animator.animatorUtils;

import org.json.JSONException;
import org.json.JSONObject;

import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

import android.animation.ObjectAnimator;
import android.animation.TimeInterpolator;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.util.SparseArrayCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.LinearInterpolator;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

public abstract class BaseHttpFragment extends Fragment implements Callback<Response> {
    private SparseArrayCompat<String> mRequestKeyArray = new SparseArrayCompat<>();
    private Dialog mDialog;
    private PopupWindow mPopupWindow;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    public abstract void initRequestAPI(String requestKeys);

    public abstract void onHttpSuccess(String url, JSONObject responseJson);
    
    public void getRawResponse(String url,Response response){ }
    
    public abstract void OnHttpFailure(String url, String errorMessage, boolean errorFromUs);

    public abstract void fetchDataFromNetwork(String key);

    /**
     * set request id (not required)
     * 
     * @param index
     * @param requestKey
     */
    public void setRequestKey(int index, String requestKey) {
        mRequestKeyArray.put(index, requestKey);
    }

    /**
     * get request id (not required)
     * 
     * @param index
     * @return
     */
    public String getRequestKeyByIndex(int index) {
        if (mRequestKeyArray != null) {
            return mRequestKeyArray.get(index);
        } else {
            return "";
        }
    }

    public int getRequestKeySize() {
        if (mRequestKeyArray != null) {
            return mRequestKeyArray.size();
        } else {
            return 0;
        }
    }

    /**
     * if need,override this fun,fetch local data from db or file
     * 
     * @param key
     * @return
     */
    public String fetchDataFromLocal(String key) {
        return SharedPreferencesHelper.getString(key);
    }

    /**
     * if need,override this fun,save data to db or file
     * 
     * @param key
     * @param responseJson
     */
    public void saveData2Local(String key, String responseJson) {
        SharedPreferencesHelper.commitString(key, responseJson);
    }

    /**
     * fetch data from local or network
     *
     * @param isFetchFromNetWork
     * @param requestKey
     */
    public void fetchData(boolean isFetchFromNetWork, String requestKey) {
        if (isFetchFromNetWork) {
            if (checkNetWorkState()) {
                fetchDataFromNetwork(requestKey);
            }
        } else {
            fetchDataFromLocal(requestKey);
        }
    }

    /**
     * check network is avaliable for better battery performance
     * 
     * @return
     */
    public boolean checkNetWorkState() {
        if (NetworkUtils.isNetworkAvaliable(SystemFramework.getInstance().getGlobalContext())) {
            return true;
        } else {
            UiUtils.showToast(getString(R.string.errcode_network_unavailable));
            return false;
        }
    }

    /**
     * retrofit sucess
     * 
     * @param baseResponse
     * @param response
     */
    @Override
    public void success(Response baseResponse, Response response) {
        String url = response.getUrl();
        String json = "";
        JSONObject jsonObject = null;
        getRawResponse(url,response);
        try {
            json = Strings.inputStream2String(response.getBody().in());
        } catch (Exception e) {
            e.printStackTrace();
            OnHttpFailure(url, SystemFramework.getInstance().getGlobalContext()
                    .getString(R.string.io_error), false);
            return;
        }

        if (!TextUtils.isEmpty(json)) {
            try {
                jsonObject = new JSONObject(json);

            } catch (JSONException e) {
                e.printStackTrace();
                OnHttpFailure(url, SystemFramework.getInstance().getGlobalContext()
                        .getString(R.string.json_error), false);
                return;
            }
        }

        // 返回error信息
        if (jsonObject != null) {
            JSONObject errorObject = jsonObject.optJSONObject("error");
            if (errorObject != null) {// 返回错误信息
                com.yimixian.app.rest.response.Error error = new Error();
                error.code = errorObject.optInt("code");
                error.message = errorObject.optString("message");
                if (!TextUtils.isEmpty(error.message)) {
                    UiUtils.showToast(error.message);
                    OnHttpFailure(url, error.message, true);
                    return;
                }
            }
        }

        onHttpSuccess(url, jsonObject);
    }

    /**
     * retrofit failure
     * 
     * @param error
     */
    @Override
    public void failure(RetrofitError error) {
        UiUtils.showToast(SystemFramework.getInstance().getGlobalContext()
                .getString(R.string.network_error));
        OnHttpFailure(error.getUrl(), error.getMessage(), false);
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

    /**
     * 显示加载框
     * 
     * @param msg 提示语
     */
    public void showDialog(String msg, boolean needToScreenFull) {
        if (!isAdded())
            return;
        if (mDialog == null) {
            mDialog = createLoadingDialog(getActivity(), msg, needToScreenFull);
        }
        mDialog.show();
//        UiUtils.showAlertDialog(mDialog);
    }

    public void showTransDialog(String msg, boolean needToScreenFull) {
        if (!isAdded())
            return;
        if (mDialog == null) {
            mDialog = createLoadingDialog(getActivity(), msg, needToScreenFull);
        }
        v.setBackgroundColor(Color.TRANSPARENT);
        mDialog.show();
//        UiUtils.showAlertDialog(mDialog);
    }

    /**
     * 隐藏加载框
     */
    public void hideDialog() {
        if (mDialog != null && mDialog.isShowing()) {
            try {
                mDialog.dismiss();
                mDialog = null;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private View v;

    /**
     * 得到自定义的progressDialog
     * 
     * @param context
     * @param msg
     * @return
     */
    public Dialog createLoadingDialog(Context context, String msg, boolean needToScreenFull) {

        LayoutInflater inflater = LayoutInflater.from(context);
        v = inflater.inflate(R.layout.progress_dialog, null);// 得到加载view
        LinearLayout layout = (LinearLayout) v.findViewById(R.id.loading_view);// 加载布局
        // main.xml中的ImageView
        TextView tipTextView = (TextView) v.findViewById(R.id.loading_text);// 提示文字
        // 加载动画
        if (!StringUtils.isEmpty(msg)) {
            tipTextView.setVisibility(View.VISIBLE);
            tipTextView.setText(msg);// 设置加载信息
        } else {
            tipTextView.setVisibility(View.GONE);
        }

        Dialog loadingDialog = new Dialog(context, R.style.loading_dialog);// 创建自定义样式dialog
        if (needToScreenFull) {
            Window win = loadingDialog.getWindow();
            win.getDecorView().setPadding(0, 0, 0, 0);
            WindowManager.LayoutParams lp = win.getAttributes();
            lp.width = WindowManager.LayoutParams.FILL_PARENT;
            lp.height = WindowManager.LayoutParams.FILL_PARENT;
            win.setAttributes(lp);
        }

        loadingDialog.setCancelable(false);// 不可以用“返回键”取消
        loadingDialog.setContentView(layout, new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT));// 设置布局
        return loadingDialog;
    }

    public void showPopupWindow(Context mContext, int id) {
        // 一个自定义的布局，作为显示的内容
        View contentView = LayoutInflater.from(mContext).inflate(
                R.layout.pop_window, null);
        if (mPopupWindow == null) {
            mPopupWindow = new PopupWindow(contentView,
                    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true) {
            };
        }
        mPopupWindow.setTouchable(true);
        mPopupWindow.setFocusable(true);
        mPopupWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });
        ColorDrawable dw = new ColorDrawable(Color.TRANSPARENT);
        mPopupWindow.setBackgroundDrawable(dw);
        mPopupWindow.setOutsideTouchable(false);
        // 设置好参数之后再show
        if (getActivity().findViewById(id) != null) {
            mPopupWindow.showAtLocation(getActivity().findViewById(id), Gravity.CENTER
                | Gravity.CENTER, 0, 0);
        }
    }

    public void hidePopupWindow() {
        if (mPopupWindow != null && mPopupWindow.isShowing()) {
            mPopupWindow.dismiss();
            mPopupWindow = null;
        }
    }
}
